#include "libutilsconfig.h"
#include "tconsolehandler.h"

#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <process.h>

LIB_NS_BEGIN

const int kBufferSize = 4096;
TStdoutHandler::TStdoutHandler(): m_thread_handle(NULL),m_pCallBack(NULL)
{

}

TStdoutHandler::~TStdoutHandler()
{
	int ret = ::_dup2(m_orign_stdout, _fileno(stdout));
}

DWORD __stdcall TStdoutHandler::RedirectThreadProc( void* param )
{
	TStdoutHandler* pInstance =  (TStdoutHandler*)param;
	 int pipe_read = pInstance->m_fds[0];

	char buf[kBufferSize];
	int bytes_read;
	do 
	{
		bytes_read = ::_read(pipe_read, buf, kBufferSize);
		buf[bytes_read] = 0;
		if(pInstance->m_pCallBack != NULL)
		{		
			pInstance->m_pCallBack(buf);
		}
	}
	while (bytes_read);
	return 0;
}

bool TStdoutHandler::StartHandler(OnDataCallBack* p)
{
	m_pCallBack = p;
	::_pipe(m_fds, kBufferSize, _O_TEXT);
	m_orign_stdout = _dup(_fileno(stdout));
	int ret =::_dup2(m_fds[0], _fileno(stdout));

	m_thread_handle = ::CreateThread(NULL, 0, RedirectThreadProc, (void*)this, 0, NULL);
	::CloseHandle((HANDLE)m_thread_handle);
	return true;
}

void TStdoutHandler::StopHandler()
{
	::TerminateThread(m_thread_handle,0);
}


LIB_NS_END